<template>
    <div class="jianzhan-content">
        <Crumb name="Working Order"/>
        <div class="content">
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Search By Request No"
                        prefix-icon="el-icon-search"/>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="workList.slice((pageNum-1) * pageSize,pageNum * pageSize)"
                        border
                        row-key="id"
                        stripe
                        style="width: 100%"
                >
                    <el-table-column type="expand" label="problem" width="80">
                        <template slot-scope="quest">
                            <div v-for="item in quest.row.problemVoList" :key="item.id">
                                <span>{{item.problemDescription}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="requestName"
                            label="Request Number"
                    />
                    <el-table-column
                            prop="workingNo"
                            label="Working Number"
                    />
                    <el-table-column
                            prop="requestDate"
                            label="Request Date"
                    />
                    <el-table-column
                            prop="requestBy"
                            label="Request By"
                    />
                    <!--<el-table-column-->
                            <!--prop="customerName"-->
                            <!--label="Customer"-->
                    <!--/>-->
                    <el-table-column
                            prop="plateNum"
                            label="PlateNum"
                    />
                    <el-table-column
                            prop="serviceType"
                            label="Service Type"
                    />
                    <el-table-column>
                        <template slot-scope="request">
                            <el-button size="small" @click="showDetail(request.row)">Working Order</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>
        </div>

        <el-dialog title="Working Order" :visible.sync="dialogVisible" width="100%" top="0">
            <quest-show :quest="quest"/>
            <div class="spin"></div>
            <el-form label-width="150px" :model="work" :rules="rule" ref="work">
                <div style="display: flex">
                    <div class="flex-content">
                        <el-form-item label="Working No">
                            <el-input disabled v-model="work.workingNo" size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item label="Date" prop="startDate">
                            <el-date-picker v-model="work.startDate" size="small" type="datetime" class="my-input"
                                            value-format="yyyy-MM-dd HH:mm:ss"/>
                        </el-form-item>
                        <!--<el-form-item label="Continue Wo No">-->
                            <!--<el-input size="small" class="my-input" v-model="work.continueWoNo"/>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="Continue Wo date">-->
                            <!--<el-date-picker size="small" class="my-input" v-model="work.continueWoDate" value-format="dd-MM-yyyy"/>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="Continue Wo Reason">-->
                            <!--<el-input size="small" class="my-input" v-model="work.continueWoReason"/>-->
                        <!--</el-form-item>-->
                    </div>
                    <div class="flex-content">
                        <el-form-item label="Field/WorkShop" prop="workingPlace">
                            <el-select v-model="work.workingPlace" size="small" class="my-input">
                                <el-option :value="0" label="Field"/>
                                <el-option :value="1" label="WorkShop"/>
                            </el-select>
                        </el-form-item>
                        <!--<el-form-item label="Sales Order No">-->
                            <!--<el-input v-model="work.salesOrderNo" size="small" class="my-input"/>-->
                        <!--</el-form-item>-->
                        <el-form-item label="SuratJalan No">
                            <el-input v-model="work.suratJalanNo" size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item label="Arrange By" prop="arrangedBy">
                            <el-select v-model="work.arrangedBy" filterable size="small" class="my-input">
                                <el-option v-for="item in employeeList" :key="item.id" :value="item.id" :label="item.employeeName"/>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="flex-content">
                        <el-form-item label="Job Receiver" required>
                            <el-select v-for="(item,index) in work.jobReceiver" filterable :key="index" v-model="item.receiverId" size="small" class="my-input">
                                <el-option v-for="item in employeeList" :key="item.id" :value="item.id" :label="item.employeeName"/>
                            </el-select>
                            <el-button type="primary" @click="addReceiver" size="small"><i class="el-icon-plus"/></el-button>
                        </el-form-item>
                        <el-form-item label="Wo Status">
                            <el-select filterable v-model="work.woStatus" size="small" class="my-input">
                                <el-option v-for="item in woStatus" :key="item.key" :value="item.key" :label="item.value"/>
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <div class="spin"></div>
            <el-button type="primary" size="small" style="margin: 20px 0;float: left" @click="dbVisible = true">Add parts <i class="el-icon-plus"/></el-button>
            <spDataBase @deleteItem="deleteItem" :partList="partList"/>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button type="primary" @click="submitForm">Confirm</el-button>
                        <el-button type="warning" @click="print">Print</el-button>
                    </span>
        </el-dialog>

        <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible"/>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import spDataBase from '@/components/part/spDataBase'
    import PartItem from '@/components/part/sparePartItem'
    import questShow from '@/components/service/questShow'
    import {getWorkingOrder, getEmployeeList, showQuestDetail, getWorkNo, getWorkDetail,getRealParts,saveWorkingOrder} from "../../api/service";
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import dbMixins from '../../util/spMixins'
    const files = [{
        problemDescription: '',
        problemPhoto: [],
        problemVideo: [],
        problemFile: []
    }];
    const quest = {
        requestNo: '',
        requestDate: '',
        initiator: '',
        customerId: '',
        customerName: '',
        addressId: '',
        address: '',
        distance: '',
        unitModel: '',
        sn: '',
        deliveryTime: '',
        hmKm: '',
        typeCode: '',
        serviceType: "",
        appointmentTime: '',
        note: '',
        status: "",
        projectName: '',
        plateNum: '',
        charges: [],
        reason:'',
        problems: [...files],
        id: '',
    };
    export default {
        name: "working-order",
        mixins: [mixins,dbMixins],
        data() {
            return {
                key: '',
                quest: {...quest},
                work: {
                    workingNo: '',
                    woStatus:0,
                    arrangedBy:'',
                    suratJalanNo:'',
                    salesOrderNo:'',
                    workingPlace:'',
                    continueWoReason:'',
                    continueWoDate:'',
                    continueWoNo:'',
                    startDate:'',
                    jobReceiver:[{receiverId:''}]
                },
                rule:{
                    workingPlace:[{required:true,message:'Working place is required'}],
                    startDate:[{required:true,message:'Start date is required'}],
                    arrangedBy:[{required:true,message:'Arranged by is required'}]
                },
                list: [],
                employeeList: [],
                dialogVisible: false,
                woStatus:[{key:0,value:'On Progress'},{key:1,value:'Wait for spareparts'},{key:2,value:'Reschedule'},{key:3,value:'Finished'},{key:4,value:'Job Continue'}]
            }
        },
        computed: {
            workList() {
                return this.list.filter(item => item.requestNo.indexOf(this.key) > -1)
            }
        },
        created() {
            this._getWorkOrder();
            this._getEmployeeList();
        },
        mounted() {
            this.$nextTick(() => {
                import('../../util/pdf.js').then(model => {
                    this.pdf = model.default;
                })
            })
        },
        methods: {
            async submitForm(){
                let flag = true;
                let {
                    workingNo,
                    startDate ,
                    // continueWoNo ,
                    // continueWoDate  ,
                    // continueWoReason ,
                    workingPlace   ,
                    // salesOrderNo ,
                    suratJalanNo ,
                    arrangedBy ,
                    woStatus ,
                    orderId  ,
                    jobReceiver} = this.work;
                jobReceiver.forEach(job=>{
                   if(!job.receiverId) {
                       flag = false
                       return false
                   }
                });
                if(!flag) {
                    this.$notify.warning('Job Receiver must not empty');
                    return false;
                }
                jobReceiver = JSON.stringify(jobReceiver);
                let sparePartsList = this.partList.map(part=>{
                    return {
                        partsId:part.id,
                        partsQuantity:part.number
                    }
                });
                sparePartsList = JSON.stringify(sparePartsList);
                this.$refs.work.validate(async valid=>{
                    if(valid) {
                        const {status} = await saveWorkingOrder({workingNo,startDate,workingPlace,suratJalanNo,arrangedBy,woStatus,orderId,jobReceiver,sparePartsList});
                        if (status === ERROR_OK) {
                            this.$message.success('Success');
                            this.dialogVisible = false;
                            this._getWorkOrder();
                            this.clear();
                        }
                    }
                })

            },
            async _getWorkOrder() {
                const {status, data} = await getWorkingOrder();
                if (status === ERROR_OK) {
                    this.list = data.list;
                    this.total = data.list.length
                }
            },
            async _getEmployeeList() {
                const {status, data} = await getEmployeeList();
                if (status === ERROR_OK) {
                    this.employeeList = data
                }
            },
            async _getDetail(id) {
                const {status, data} = await showQuestDetail(id);
                if (status === ERROR_OK) {
                    this.quest = data.orderVo;
                    if (data.problemVoList.length) {
                        this.$set(this.quest, 'problems', data.problemVoList);
                    } else {
                        this.$set(this.quest, 'problems', [{
                            problemDescription: '',
                            problemPhoto: [],
                            problemVideo: [],
                            problemFile: []
                        }])
                    }
                    this.quest.problems = data.problemVoList

                }
            },
            async _getWorkNo() {
                const {status, data} = await getWorkNo();
                if (status === ERROR_OK) {
                    this.work.workingNo = data
                }
            },
            async _getRealPart(workOrderNo){
                const {status,data} = await getRealParts(workOrderNo);
                if(status === ERROR_OK) {
                    this.partList = data.map(part=>{
                        return {
                            ...part.spareParts,
                            number:part.partsQuantity
                        }
                    })
                } else {
                    this.partList = []
                }
            },
            async _getWorkDetail(id) {
                const {status, data} = await getWorkDetail(id);
                if (status === ERROR_OK) {
                    this.work = data;
                    this.$set(this.work,'jobReceiver',data.jobReceiverVoList);
                    this.partList = data.partsList.map(part=>{
                        return {
                            ...part,
                            number:part.quantity,
                            quantity:part.sparePartsStock,
                        }
                    });
                }
            },
            clear(){
                this.work = {
                    workingNo: '',
                    woStatus:0,
                    arrangedBy:'',
                    suratJalanNo:'',
                    salesOrderNo:'',
                    workingPlace:'',
                    continueWoReason:'',
                    continueWoDate:'',
                    continueWoNo:'',
                    date:'',
                    jobReceiver:[{receiverId:''}]
                }
            },
            addReceiver(){
                if(!this.work.jobReceiver) {
                    this.$set(this.work,'jobReceiver',[{receiverId:''}])
                } else {
                    this.work.jobReceiver.push({
                        receiverId:''
                    })
                }

            },
            showDetail(work) {
                this._getDetail(work.id);
                if (!work.workingNo) {
                    this.clear();
                    this._getWorkNo();
                    this.partList = [];
                } else {
                    this._getWorkDetail(work.workingId);
                    // this._getRealPart(work.workingNo);
                }

                this.dialogVisible = true;
                this.work.orderId =work.id
            },
            print(){
                let parts = '';
                let receiver = '';
                this.partList.forEach((part,index)=>{
                   parts += `${index+1} .${part.partsNumber}  ${part.number}PC \n`
                });
                this.work.jobReceiverVoList.forEach(item=>{
                    receiver += `${item.receiverName}\n`
                });
                let doc = {
                    filename: 'QO',
                    pageSize: 'LEGAL',
                    pageMargins: [10, 200, 10, 20],
                    header: [
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '70%',
                                    text: [
                                        {
                                            text: 'PT INDONESIA EQUIPMENT LINE\n',
                                            style: 'header'
                                        },
                                        {
                                            text: "Leading in Service Innovation\n",
                                            style: 'subTitle'
                                        },
                                        ' No.17-18 Blok A, Ruko Inkopal Kelapa Gading \n',
                                        ' Jl. Boulevard Barat Raya Jakarta Utara 14240 Indonesia \n',
                                        ' Tel: 0800-1581212\n',
                                        ' Tel: 021- 89914964 / 021-45859155'
                                    ],

                                },
                                {
                                    width: '*',
                                    text: 'Working Order',
                                    style: 'title',
                                    alignment: 'right'
                                }
                            ],
                        },
                        {
                            margin: [20, -10, 20, 20],
                            columns: [
                                {
                                    width: '*',
                                    text: [
                                        `Date: ${this.quest.requestDate}\n`,
                                        `Request: ${this.quest.requestNo}\n`,
                                        `Working Order : ${this.work.workingNo}\n`,
                                        `Surat Jalan: ${this.work.suratJalanNo}`
                                    ],
                                    alignment:'right'
                                }
                            ]
                        }
                    ],
                    content: [
                        {
                            margin: [0, 0, 0, 0],
                            table: {
                                headerRows:0,
                                style:'column',
                                widths:['50%','50%'],
                                heights:[150,150],
                                body:[
                                  [
                                      `Customer:${this.quest.customerName}\nService Address:${this.quest.address}\nLocation:${this.quest.distance}\nContact Pic:\nContact No:\n`,
                                      `Unit model:${this.quest.unitModel}\nSn:${this.quest.sn}\nHour Meter:${this.quest.hmKm}\nJob Type:${this.quest.serviceType}`
                                  ]
                                ]
                            }
                        },
                        {
                            margin: [0, 20, 0, 0],
                            table: {
                                headerRows:0,
                                style:'column',
                                widths:['50%','50%'],
                                heights:[100,100],
                                body:[
                                    [
                                        'Problem Description:',
                                        'Suggestion:'
                                    ]
                                ]
                            }
                        },
                        {
                            width: '*',
                            text: 'Spareparts Suggestion / Spareparts Used',
                            alignment: 'left'
                        },
                        {
                            margin: [0, 0, 0, 0],
                            table: {
                                headerRows:0,
                                style:'column',
                                widths:['100%'],
                                heights:[100],
                                body:[
                                    [
                                        parts
                                    ]
                                ]
                            }
                        },
                        {
                            width: '*',
                            text: 'note',
                            alignment: 'left'
                        },
                        {
                            margin: [0, 0, 0, 0],
                            table: {
                                headerRows:0,
                                style:'column',
                                widths:['100%'],
                                heights:[100],
                                body:[
                                    [
                                        ''
                                    ]
                                ]
                            }
                        },
                        {
                            margin: [30, 0, 0, 0],
                            alignment:'center',
                            columns: [
                                {
                                    width: '33%',
                                    text: [
                                        `Receiver Order\n`,
                                        receiver
                                    ],

                                },
                                {
                                    width:'33%',
                                    text:[
                                        'Giving Order\n',
                                        this.work.arrangedByDesc
                                    ]
                                },
                                {
                                    width: '*',
                                    text: 'Customer Pic',
                                }
                            ],
                        },
                        {
                            margin:[0,30,0,0],
                            text:[
                                'Arrived at location\n',
                                'Finish Job\n',
                                'Leaving the Job Site'
                            ]
                        }

                    ],
                    footer: [
                        {
                            text: 'If you have any questions or concerns, please contact 0800-1581212',
                            width: '100%',
                            alignment: 'center'
                        },
                        {text: 'THANK YOU FOR YOUR BUSINESS! ', width: '100%', alignment: 'center'}
                    ],

                    defaultStyle: {
                        font: 'msyh'
                    },

                    styles: {
                        header: {
                            fontSize: 15,
                            bold: true
                        },
                        title: {
                            fontWeight: 'light',
                            fontSize: 25,
                            bold: false
                        },
                        subTitle: {
                            fontSize: 12,
                            bold: true,
                            italic: true
                        }
                    }

                };
                this.pdf.open(doc);
            }
        },
        components: {
            Crumb, Search, spDataBase, PartItem,questShow
        },
        watch: {
            workList(list) {
                this.total = list.length
            }
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";
    .content {
        @include content
    }
    .spin {
        border-bottom: 2px dashed #ddd;
        width: 100%;
        height: 0;
        margin-top: 20px;
    }
</style>